-- qps计数器

local ngx = ngx

local t_cacheQps = ngx.shared.misQps

local mis_log = nil
local mis_config = nil
local t_retCode = nil

--------------------------------------------------------------
local mis_qps = {
	s_name = string.match(debug.getinfo(1).short_src, '.*/(.*).lua');	-- 模块名称
}
local this = mis_qps
local n_m_logTimer = 0													-- 时间计数器
local t_m_qpsCounter = {
	["10.20.60.35_3306"] = 0,
	["10.20.20.15_3306"] = 0,
	["10.20.10.140_3306"] = 0,
	["wealth_god"]    = 0,
}												-- qps统计

--------------------------------------------------------------
-- 说明：qps计数回调
local function qps_timer_callback(premature)
	if premature then return end
	local n_
	local s_out = ''
	n_m_logTimer = n_m_logTimer + 1
	for s_key, _ in pairs(t_m_qpsCounter) do
		if n_m_logTimer >= mis_config.n_qpsLogInterval then
			n_ = t_cacheQps:get(s_key)
			if n_ then s_out = s_out .. string.format("%s:%.01f/s ", s_key, n_) end
		end
		t_cacheQps:delete(s_key)
		t_m_qpsCounter[s_key] = 0
	end
	if #s_out > 0 then
		mis_log.day('mis_qps', s_out)
	end
	if n_m_logTimer >= mis_config.n_qpsLogInterval then
		n_m_logTimer = 0
	end
end

--------------------------------------------------------------
-- 说明：模块包含
-- 参数：模块表
this.modules_include = function(t_moddules)
	mis_log = t_moddules.mis_log
	mis_config = t_moddules.mis_config
	t_retCode = mis_config.t_retCode
end

--------------------------------------------------------------
-- 说明：load级初始化
this.init_load = function()
	if ngx.worker.id() == 0 then
		local _, s_err = ngx.timer.every(1, qps_timer_callback)
		if s_err then
			s_err = 'start timer failed, ' .. s_err
			mis_log.error(s_err)
			return t_retCode.n_SYS_ERR, s_err
		end
	end
	return t_retCode.n_OK
end

--------------------------------------------------------------
-- 说明：打标记
-- 参数：s_key		标记ID
-- 返回：n			当前qps
this.mark = function(s_key)
	local n_, s_err = t_cacheQps:incr(s_key, 1, 0)
	if s_err then
		mis_log.warning('incr shared dict misQps failed.')
		return 0
	end
	t_m_qpsCounter[s_key] = n_
	return n_
end

--------------------------------------------------------------
-- 说明：查看当前qps
-- 参数：s_key		标记ID
-- 返回：n			当前qps
this.watch = function(s_key)
	return t_m_qpsCounter[s_key] or 0
end

return this